package JPetStore.web.servlet;

import JPetStore.domain.Account;
import JPetStore.domain.Product;
import JPetStore.service.CatalogService;
import JPetStore.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

public class SearchProductServlet extends HttpServlet {
    private static final String SEARCH = "/WEB-INF/jsp/catalog/search.jsp";
    private String keyword;

    public SearchProductServlet() {
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.keyword = req.getParameter("keyword");
        CatalogService service = new CatalogService();
        List<Product> productList = service.searchProductList(this.keyword);
        HttpSession session = req.getSession();
        session.setAttribute("keyword", this.keyword);
        session.setAttribute("productList", productList);
        Account loginAccount = (Account)session.getAttribute("loginAccount");
        if (loginAccount != null) {
            String username = loginAccount.getUsername();
            String strBackUrl = "http://" + req.getServerName() + ":" + req.getServerPort()
                    + req.getContextPath() + req.getServletPath() + "?" + (req.getQueryString());
            LogService logService = new LogService();
            String logInfo = logService.logInfo(new Object[]{" "}) + strBackUrl + "查询了"+this.keyword;
            logService.insertLogInfo(username, logInfo);
        }
        req.getRequestDispatcher(SEARCH).forward(req, resp);
    }
}
